package com.ld.hpfs.web.interseptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ld.hpfs.web.controller.LoginController;

/**
 * 验证用户登陆拦截器
 * 
 * @author bole
 * @date 2012-8-16 下午09:02:00
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        logger.debug("URI = {}, {}, {}", new Object[] { request.getRequestURI(), request.getRequestedSessionId(), request.getRequestURL().toString()});
        
        String actionString = request.getRequestURI().split("/")[2];
        if (actionString.equals("getUserState") ||
            actionString.equals("getCompany")) return true;        
        
        // 如果session中没有user对象
        if (null == request.getSession().getAttribute(WebConstants.CURRENT_USER)) {
            String requestedWith = request.getHeader("x-requested-with");
            // ajax请求
            if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)) {
                response.setHeader("session-status", "timeout");
                response.getWriter().print(WebConstants.TIME_OUT);
                response.setStatus(404);
//                response.sendRedirect(request.getContextPath() + "/timeout");
            } else {
                // 普通页面请求
                response.sendRedirect(request.getContextPath() + "/");
            }

            logger.debug(request.getContextPath());
            return false;
        }
        return true;

    }

}
